import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Popconfirm,
  Button,
  Modal,
  message,
  Badge,
  DatePicker,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './Coupon.less';

const { RangePicker } = DatePicker;
const FormItem = Form.Item;
const { Option } = Select;

const statusMap = ['success', 'error'];
const status = ['上架', '废弃'];

@connect(({ coupon, loading }) => ({
  coupon,
  loading: loading.models.coupon,
}))
@Form.create()
export default class Coupon extends PureComponent {
  state = {
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},

    startTime: null,
    endTime: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'coupon/fetchCouponList',
      payload: { "pageNum": "1", "pageSize": "10" }
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    // console.log('分页条件', this.props.form.getFieldValue())

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
      startTime: this.state.startTime ? this.state.startTime.format('YYYY-MM-DD') : null,
      endTime: this.state.endTime ? this.state.endTime.format('YYYY-MM-DD') : null,
    };

    dispatch({
      type: 'coupon/fetchCouponList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();

    this.setState({ startTime: null, endTime: null })

    dispatch({
      type: 'coupon/fetchCouponList',
      payload: {
        pageNum: 1,
        pageSize: this.props.coupon.pagination.pageSize ? this.props.coupon.pagination.pageSize : 10,
      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch() {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      delete fieldsValue.time;

      const values = {
        ...fieldsValue,
        startTime: this.state.startTime ? this.state.startTime.format('YYYY-MM-DD') : null,
        endTime: this.state.endTime ? this.state.endTime.format('YYYY-MM-DD') : null,
        pageNum: 1,
        pageSize: this.props.coupon.pagination.pageSize ? this.props.coupon.pagination.pageSize : 10,
      };

      dispatch({
        type: 'coupon/fetchCouponList',
        payload: values,
      });
    });
  };

  disabledStartDate = (startTime) => {
    const endTime = this.state.endTime;
    if (!startTime || !endTime) {
      return false;
    }
    return startTime.valueOf() > endTime.valueOf();
  }

  disabledEndDate = (endTime) => {
    const startTime = this.state.startTime;
    if (!endTime || !startTime) {
      return false;
    }
    return endTime.valueOf() <= startTime.valueOf();
  }

  onChange = (field, value) => {
    this.setState({
      [field]: value,
    });
  }

  onStartChange = (value) => {
    this.onChange('startTime', value);
  }

  onEndChange = (value) => {
    this.onChange('endTime', value);
  }

  _deleteCoupon(selectedRows) {
    if (selectedRows && selectedRows.length > 0) {
      let recordList = [];
      for (let i in selectedRows) {
        let one = { couponId: selectedRows[i].couponId }
        recordList.push(one)
      }

      if (recordList) {
        this.props.dispatch({
          type: 'coupon/deleteCoupon',
          payload: { couponIdList: recordList },
          callback: () => { this.handleSearch(); this.setState({ selectedRows: [] }) }
        });
      }
    } else {
      message.error('请选择内容')
    }
  }


  _timeOnChange(value, dateString) {
    console.log('Selected Time: ', value);
    console.log('Formatted Selected Time: ', dateString);
    if (!(value && value.length > 0)) {
      this.setState({ startTime: null, endTime: null })
    } else {
      this.setState({ startTime: value[0].format('YYYY-MM-DD'), endTime: value[1].format('YYYY-MM-DD') })
    }
  }

  _timeOk(value) {
    console.log('onOk: ', value);
    this.setState({ startTime: value[0].format('YYYY-MM-DD'), endTime: value[1].format('YYYY-MM-DD') })
  }

  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="所属App">
              {getFieldDecorator('appType', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="1">小萌早教</Option>
                  <Option value="2">小萌绘本</Option>
                  <Option value="3">积分商城</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('couponSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="0">上架</Option>
                  <Option value="1">废弃</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="优惠券名称">{getFieldDecorator('couponName')(<Input />)}</FormItem>
          </Col>
        </Row>
        <Row>
          <FormItem label="有效期">
            {getFieldDecorator('startTime')(
              <DatePicker
                disabledDate={this.disabledStartDate}
                format="YYYY-MM-DD"
                placeholder="请选择"
                onChange={this.onStartChange}
              />
            )}
            --
            {/* </FormItem>
            <FormItem label="注册结束时间"> */}
            {getFieldDecorator('endTime')(
              <DatePicker
                disabledDate={this.disabledEndDate}
                format="YYYY-MM-DD"
                placeholder="请选择"
                onChange={this.onEndChange}
              />
            )}
          </FormItem>
        </Row>



        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()} >
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </span>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    const {
      loading,
    } = this.props;

    const tableData = {}
    tableData['list'] = this.props.coupon.couponList;
    tableData['pagination'] = this.props.coupon.pagination;

    const { selectedRows, modalVisible } = this.state;

    const columns = [
      {
        title: '优惠券名称',
        dataIndex: 'couponName',
        key: 'couponName',
      },
      {
        title: '分类',
        dataIndex: 'couponType',
        key: 'couponType',
        render(val) {
          return <span>{val == '0' ? '抵用券' : val == '1' ? '折扣券' : '其他'}</span>;
        },
      },
      {
        title: '优惠面额/折扣',
        dataIndex: 'moneyDiscount',
        key: 'moneyDiscount ',
        render(val) {
          return val + '元';
        },
      },
      {
        title: '使用条件',
        dataIndex: 'requiredAmt',
        key: 'requiredAmt',
        render(val) {
          return val + '元';
        },
      },
      {
        title: '有效期',
        dataIndex: 'expireTime',
        key: 'expireTime',
      },
      {
        title: '状态',
        dataIndex: 'couponSts',
        key: 'couponSts',
        render(val) {
          return <Badge status={statusMap[val]} text={status[val]} />;
        },
      },
      {
        title: '关联App',
        dataIndex: 'appType',
        key: 'appType',
        render(val) {
          return <span>{val == '0' ? '不限' : val == '1' ? '小萌早教' : val == '2' ? '小萌绘本' : '其他'}</span>;
        },
      },
      {
        title: '操作',
        key: '操作',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/coupon/couponItem/' + record.couponId }))}>编辑</a>
          </Fragment>
        ),
      },
    ];


    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/coupon/couponItem/new' }))}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Popconfirm title="确定要删除选中的优惠券吗?" placement="bottom" onConfirm={() => this._deleteCoupon(selectedRows)} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="danger" icon="upload" >
                      删除
                  </Button>
                  </Popconfirm>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              rowKey={"couponId"}
              data={tableData}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    );
  }
}
